#include"TcpServer.hpp"
#include"ThreadPool.hpp"

#define PORT 8080


class HttpServer
{
  private:
    int _port;
    TcpServer* ts;
    ThreadPool* tp;
  public:
    HttpServer(int port=PORT):_port(port),ts(nullptr)
  {
    signal(SIGPIPE,SIG_IGN);//客户端若在服务器写数据时关闭管道,服务器会收到SIGPIPE信号
                            //该信号默认处理动作是杀死进程,所以要忽略掉
                            
  }

    ~HttpServer()
    {
      if(ts==nullptr)
        delete ts;
    }

    void Init()
    {
     ts=new TcpServer(_port);
     ts->Init();
     LOG(INFO,"TcpServer Init Success");
         
     tp=new ThreadPool();
     tp->InitThreadPool();
    }

    void Loop()
    {
      sockaddr_in peer;
      socklen_t len;
      LOG(INFO,"Start Loop");
        while(1)
        {
                       
          int sock=ts->Accept(&peer,&len);
          if(sock<0)
            LOG(WARNING,"Accept Error!");
          else
          {
            std::string ip=inet_ntoa(peer.sin_addr);
            int port=ntohs(peer.sin_port);
            LOG(INFO,"---------Accpet Success---------- peer :"+ip+":"+std::to_string(port));
          }
           
       //   int *newsock=new int(sock);
       //   pthread_t tid;
       //   pthread_create(&tid,nullptr,HandleRequest,newsock);
       //   pthread_detach(tid);
         
          Task t(sock);
          tp->PushTask(t);
        }


    }
};

